package com.hk.dyeyuesystem;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hk.dyeyuesystem.db.DBOpenHelper;
import com.hk.dyeyuesystem.util.DateUtil;
import com.hk.dyeyuesystem.util.RegexUtil;
import com.hk.dyeyuesystem.util.ToastUtil;

import java.util.Date;

/**
 * 新增图书相关操作
 */
public class BookAddActivity extends AppCompatActivity implements View.OnFocusChangeListener {

    //  Initialize Toast
    private Toast toast;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

//    Initialize EditText Button
    private EditText bookNumber,bookName,bookAuthor,bookPress,bookCount;

    private Button bookAddBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_add);
//        实例化
        dbOpenHelper = new DBOpenHelper(BookAddActivity.this, "db_book_system", null, 1);
//        获取个EditText编辑框控制权
        bookNumber = findViewById(R.id.book_add_number);
        bookName = findViewById(R.id.book_add_name);
        bookAuthor = findViewById(R.id.book_add_author);
        bookPress = findViewById(R.id.book_add_press);
        bookCount = findViewById(R.id.book_add_count);
//        触发编辑框焦点事件
        bookName.setOnFocusChangeListener(this);
        bookNumber.setOnFocusChangeListener(this);
//        获取到Button的控制权
        bookAddBtn = findViewById(R.id.book_add_btn);
//        创建按钮点击事件
        bookAddBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //                获取图书编号、图书名称、作者、出版社、数量
                String bookNumberToString = bookNumber.getText().toString();
                String bookNameToString = bookName.getText().toString();
                String bookAuthorToString = bookAuthor.getText().toString();
                String bookPressToString = bookPress.getText().toString();
                String bookCountToString = bookCount.getText().toString();
                // 校验图书各数据
                Boolean check = checkBookData(bookNumberToString,bookNameToString,bookAuthorToString,bookPressToString,bookCountToString);
                if (check) { // 开始新增图书
                    SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//                    封装需要新增的图书信息
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("BOOK_NUMBER",bookNumberToString);
                    contentValues.put("BOOK_NAME",bookNameToString);
                    contentValues.put("AUTHOR",bookAuthorToString);
                    contentValues.put("PRESS",bookPressToString);
                    contentValues.put("BOOK_NUM",bookCountToString);
                    contentValues.put("NUMBER_REMAINING",bookCountToString);
                    contentValues.put("CREATE_TIME", DateUtil.dateString(new Date()));
                    contentValues.put("UPDATE_TIME", DateUtil.dateString(new Date()));
//                    执行新增图书
                    readableDatabase.insert("BOOK",null,contentValues);
                    toast = ToastUtil.toastHint(toast, BookAddActivity.this, "图书新增成功，请返回进行查看！");
                    return;
                }

            }
        });


    }



    /**
     * 逐个校验数据是否符合规则
     * @param bookNumberToString  图书编号
     * @param bookNameToString 图书名称
     * @param bookAuthorToString 图书作者
     * @param bookPressToString 图书出版社
     * @param bookCountToString 图书数量
     * @return
     */
    private Boolean checkBookData(String bookNumberToString, String bookNameToString, String bookAuthorToString, String bookPressToString, String bookCountToString) {
//        校验图书编号
        if (bookNumberToString.equals("") || bookNumberToString.equals(null) || bookNumberToString == null) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"图书编号不能为空！");
            return false;
        }
        if (RegexUtil.checkBlankSpace(bookNumberToString)) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"图书编号不能包含空格！");
            return false;
        }
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("BOOK", null, "BOOK_NUMBER = ?", new String[]{bookNumberToString}, null, null, null);
        if (cursor.moveToNext()) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"该图书编号已被使用，请更换！");
            return false;
        }
//        开始校验图书名称
        if (bookNameToString.equals("") || bookNameToString.equals(null) || bookNameToString == null) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"图书名称不能为空！");
            return false;
        }
        if (RegexUtil.checkBlankSpace(bookNameToString)) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"图书名称不能包含空格！");
            return false;
        }

        Cursor cursor2 = readableDatabase.query("BOOK", null, "BOOK_NAME = ?", new String[]{bookNameToString}, null, null, null);
        if (cursor2.moveToNext()) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"该图书名称已被使用，请更换！");
            return false;
        }

//        开始校验图书作者
        if (bookAuthorToString.equals("") || bookAuthorToString.equals(null) || bookAuthorToString == null) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"图书作者不能为空！");
            return false;
        }
        if (RegexUtil.checkBlankSpace(bookAuthorToString)) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"图书作者不能包含空格！");
            return false;
        }
        if (!RegexUtil.checkChinese(bookAuthorToString)) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"图书作者为中文！");
            return false;
        }
//        开始校验出版社
        if (bookPressToString.equals("") || bookPressToString.equals(null) || bookPressToString == null) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"出版社不能为空！");
            return false;
        }
        if (RegexUtil.checkBlankSpace(bookPressToString)) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"出版社不能包含空格！");
            return false;
        }
        if (!RegexUtil.checkChinese(bookPressToString)) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"出版社为中文！");
            return false;
        }
//        开始校验数量
        if (bookCountToString.equals("") || bookCountToString.equals(null) || bookCountToString == null) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"数量不能为空！");
            return false;
        }
        if (RegexUtil.checkBlankSpace(bookCountToString)) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"数量不能包含空格！");
            return false;
        }
        if (!RegexUtil.checkDigitz(bookCountToString)) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"数量为正整数！");
            return false;
        }
        return true;
    }

    /**
     * 焦点触发事件
     * @param v
     * @param hasFocus
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.book_add_number:
                if (hasFocus) break;
//                获取图书编号
                String bookNumberToString = bookNumber.getText().toString();
//                校验图书编号
                checkBookNumber(bookNumberToString);
                break;
            case R.id.book_add_name:
                if (hasFocus) break;
//                获取图书名称
                String bookNameToString = bookName.getText().toString();
//                校验图书名称
                checkBookName(bookNameToString);
                break;
        }

    }

    /**
     * 校验图书名称
     * @param bookNameToString 图书名称
     */
    private void checkBookName(String bookNameToString) {
        if (bookNameToString.equals("") || bookNameToString.equals(null) || bookNameToString == null) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"图书名称不能为空！");
            return;
        }

        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("BOOK", null, "BOOK_NAME = ?", new String[]{bookNameToString}, null, null, null);
        if (cursor.moveToNext()) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"该图书名称已被使用，请更换！");
            return;
        }

    }

    /**
     * 校验图书编号
     * @param bookNumber 图书编号
     */
    private void checkBookNumber(String bookNumber) {
        if (bookNumber.equals("") || bookNumber.equals(null) || bookNumber == null) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"图书编号不能为空！");
            return;
        }
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("BOOK", null, "BOOK_NUMBER = ?", new String[]{bookNumber}, null, null, null);
        if (cursor.moveToNext()) {
            toast = ToastUtil.toastHint(toast,BookAddActivity.this,"该图书编号已被使用，请更换！");
            return;
        }

    }

    /**
     * 重写onKeyDown()方法来拦截用户单击后退按钮事件
     * @param keyCode 按键标识
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        判断按下的是否为后退按键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            返回上一页标识是否刷新
//            setResult(RESULT_OK,new Intent());
            startActivityForResult(new Intent(BookAddActivity.this,BookAdminActivity.class),RESULT_OK);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}